package utils
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.utils.Dictionary;
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;

	/** 
	 * 用于显示对象的对象池类  
	 */
	public class DisplayObjectPool 
	{
		
		private static  var _instance:DisplayObjectPool;
		/** 
		 *  作为对象池的词典dict 
		 */
		private const objPoolDict:Dictionary=new Dictionary(true);
		
		public static function get instance():DisplayObjectPool
		{
			return _instance ||= new DisplayObjectPool;
		}
		
		/** 
		 * 向对象池中放入对象，以便重复利用 
		 * @param disObj 要的放入对象 
		 
		 */
		public function push(oldObj:Object):void
		{
			
			var objName:String=getQualifiedClassName(oldObj);
			
			if (oldObj == null) 
				return;
			
			if (this.objPoolDict[objName] == null) 
			{
				this.objPoolDict[objName]=[];
			}
			this.objPoolDict[objName].push(oldObj);
		}
		
		/** 
		 * 从对象池中取出需要的对象 
		 * @param targetObj 需要的对象类类名，没必要必须是类实例名 类名就可以 
		 * @return 取出的相应对象 
		 */
		public function pop(targetObj:Object):Object 
		{
			
			var objName:String=getQualifiedClassName(targetObj);
			
			trace(objName);
			
			if (this.objPoolDict[objName] != null && this.objPoolDict[objName].length > 0)
			{
				
				return this.objPoolDict[objName].pop()  as  Object;
				
			}
			
			var objClass:Class=getDefinitionByName(objName)  as  Class;
			
			var obj:Object=new objClass as Object;
			
			return obj;
		}
		
		/**
		 * 从对象池中获取网络图片的bitmapdata
		 */
		public function popBitmapData(url:String):BitmapData
		{
			return objPoolDict[url];
		}
		
		/**
		 * 向对象池中放入网络数据，
		 * @param url	网络图片路径
		 * @param obj	bitmap / bitmapdata
		 */
		public function pushBitmapData(url:String, obj:Object):void
		{
			if(obj is Bitmap)
				objPoolDict[url] = (obj as Bitmap).bitmapData.clone();
			else if(obj is BitmapData)
				objPoolDict[url] = obj;
		}
	}
	
}